package com.guoguo.api;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.guoguo.base.BaseController;
import com.guoguo.base.PageBean;
import com.guoguo.base.StaticResource;
import com.guoguo.entity.Attention;
import com.guoguo.entity.Comment;
import com.guoguo.entity.Favorite;
import com.guoguo.entity.Model;
import com.guoguo.entity.vo.AcAlbumImagesVO;
import com.guoguo.entity.vo.AlbumCategoryVO;
import com.guoguo.entity.vo.AlbumImagesVO;
import com.guoguo.entity.vo.AttentionVO;
import com.guoguo.entity.vo.CategoryAlbumVO;
import com.guoguo.entity.vo.CategoryVO;
import com.guoguo.entity.vo.CommentVO;
import com.guoguo.entity.vo.FavoriteVO;
import com.guoguo.entity.vo.ModelAlbumVO;
import com.guoguo.entity.vo.ModelVO;
import com.guoguo.entity.vo.ModelsVO;
import com.guoguo.entity.vo.ReplysVO;
import com.guoguo.entity.vo.SysImgVO;
import com.guoguo.enums.UsersEnum;
import com.guoguo.service.AlbumService;
import com.guoguo.service.AttentionService;
import com.guoguo.service.AuthorService;
import com.guoguo.service.CommentService;
import com.guoguo.service.FavoriteService;
import com.guoguo.service.IAcCategoryAlbumService;
import com.guoguo.service.ICategoryService;
import com.guoguo.service.IImagesService;
import com.guoguo.service.IReplysService;
import com.guoguo.service.IUserExtService;
import com.guoguo.service.ModelAlbumService;
import com.guoguo.service.ModelsService;
import com.guoguo.service.UserFavouriteService;
import com.guoguo.utils.ClazzUtils;
import com.guoguo.utils.HttpClient;
import com.guoguo.utils.RedisUtils;
import com.guoguo.utils.UUIDUtils;

/**
 * Created by Administrator on 2017/8/9 0009.
 */
@RestController
@RequestMapping("/api/category")
public class ImagesController extends BaseController {


    @Resource
    private ICategoryService iCategoryService;

    @Resource
    private IAcCategoryAlbumService iAcCategoryAlbumService;

    @Resource
    private IImagesService iImagesService;

    @Resource
    private IReplysService iReplysService;

    @Resource
    private ModelsService iModelsService;
    @Resource
    private ModelAlbumService iModelAlbumService;
    @Resource
    private CommentService commentService;
    @Resource
    private AttentionService attentionService;
    @Resource
    private AlbumService albumService;
    @Resource
    private AuthorService authorService;
    @Resource
    private FavoriteService favoriteService;
    @Resource
    private UserFavouriteService userFavouriteService;

    @Autowired
    private IUserExtService iUserExtService;

    /**
     * 图片分类
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getCategoryList", method = RequestMethod.POST)
    public JSONObject getCategoryList() {
        List<CategoryVO> categories = iCategoryService.getCategoryList();
        return returnResult(200, categories, "");
    }


    /**
     * 获取系统图片（轮播图片和启动页图片）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getImages", method = RequestMethod.POST)
    public JSONObject getImages() {
        PageBean<SysImgVO> SysImagesVOs = iImagesService.getImages();
        return returnResult(200, SysImagesVOs, "");
    }

    /**
     * 专辑列表
     *
     * @param cateId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAlbumList", method = RequestMethod.POST)
    public JSONObject getAlbumList(@RequestParam String cateId, int cateType, int pageNum, int pageSize) {
        Map<String, Object> data = new HashMap();
        if (pageNum > 0) {
            PageBean<CategoryAlbumVO> albumList = iAcCategoryAlbumService.getCategoryAlbumList(cateId, cateType, pageNum, pageSize);
            return returnResult(200, albumList, "");
        } else {
            return returnResult(UsersEnum.PAGE_PARAM_ERROR.getId(), data, UsersEnum.PAGE_PARAM_ERROR.getValue());
        }

    }

    /**
     * 专辑图片列表
     *
     * @param albId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAlbumImageList", method = RequestMethod.POST)
    public JSONObject getAlbumImageList(@RequestParam String albId, @RequestParam int pageNum, @RequestParam int pageSize) {
        Map<String, Object> data = new HashMap();
        if (pageNum > 0) {
            PageBean<AlbumImagesVO> albumImageList = iImagesService.getAlbumImagesList(albId, pageNum, pageSize);

            return returnResult(200, albumImageList, "");
        } else {
            return returnResult(UsersEnum.PAGE_PARAM_ERROR.getId(), data, UsersEnum.PAGE_PARAM_ERROR.getValue());
        }

    }

    /**
     * 图片详情
     *
     * @param albId
     * @param modelId
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getImagesById", method = RequestMethod.POST)
    public JSONObject getImagesById(@RequestParam String albId, String modelId, String userId) {
        Map<String, Object> data = new HashMap();
        PageBean<AcAlbumImagesVO> albumImageList = iImagesService.getImagesById(albId);
        return returnResult(200, albumImageList, "");


    }

    /**
     * 专辑所属分类
     *
     * @param albId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getCategoryAlbum", method = RequestMethod.POST)
    public JSONObject getCategoryAlbum(@RequestParam String albId, int pageNum) {
        Map<String, Object> data = new HashMap();
        if (pageNum > 0) {
            PageBean<AlbumCategoryVO> categoryList = iAcCategoryAlbumService.getCategoryAlbum(albId, pageNum);
            return returnResult(200, categoryList, "");

        } else {
            return returnResult(UsersEnum.PAGE_PARAM_ERROR.getId(), data, UsersEnum.PAGE_PARAM_ERROR.getValue());
        }

    }

    /**
     * 查看图片评论列表
     *
     * @param imgId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getCommentList", method = RequestMethod.POST)
    public JSONObject getCommentList(@RequestParam String imgId, int pageNum, int pageSize) {
        Map<String, Object> data = new HashMap();
        if (pageNum > 0) {
            PageBean<CommentVO> commentVO = iImagesService.getCommentList(imgId, pageNum, pageSize);
            PageBean<CommentVO> hotCommentVO = iImagesService.getHotCommentList(imgId, pageNum, pageSize);
            Map map = new HashMap();
            map.put("commentVO", commentVO);
            map.put("hotCommentVO", hotCommentVO);
            return returnResult(200, map, "");
        } else {
            return returnResult(UsersEnum.PAGE_PARAM_ERROR.getId(), data, UsersEnum.PAGE_PARAM_ERROR.getValue());
        }


    }

    /**
     * 查看专辑评论列表
     *
     * @param albId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAlbumComment", method = RequestMethod.POST)
    public JSONObject getAlbumComment(@RequestParam String albId, int pageNum, int pageSize) {
        Map<String, Object> data = new HashMap();
        if (pageNum > 0) {
            PageBean<CommentVO> commentVO = albumService.getAlbumComment(albId, pageNum, pageSize);
            PageBean<CommentVO> hotCommentVO = albumService.getHotAlbumComment(albId, pageNum, pageSize);
            Map map = new HashMap();
            map.put("commentVO", commentVO);
            map.put("hotCommentVO", hotCommentVO);
            return returnResult(200, map, "");
        } else {
            return returnResult(UsersEnum.COMMENT_ERROR.getId(), data, UsersEnum.COMMENT_ERROR.getValue());
        }
    }

    /**
     * 发表评论
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendComment", method = RequestMethod.POST)
    public JSONObject sendCommennt(String userId, int commType, String commContent, String albId, String imgId,HttpServletRequest request) {

        Map<String, Object> data = new HashMap();
        String dealcomment = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("keyName", commContent);
		String getServerPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
		String url = getServerPath +"/sensitive-word-filter/sensitive/dealSensitive";
		try {
			data = HttpClient.post(url,params);
		} catch (Exception e) {
			e.printStackTrace();
			return (JSONObject) new JSONObject().put("code", "40004");
		}
        Comment comment = new Comment();
        comment.setCommId(UUIDUtils.getUUID());
        /*try {
            comment.setCommContent(new String(commContent.getBytes("iso-8859-1"), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        dealcomment = data.get("data").toString();
        if(StringUtils.isNotBlank(dealcomment) && dealcomment.length() > 9){
        	dealcomment=dealcomment.substring(9);
        	if(dealcomment.length() > 2){
        		dealcomment = dealcomment.substring(0, dealcomment.length()-2);
        	}
        }
        comment.setCommContent(dealcomment);
        comment.setCommType(commType);
        comment.setUserId(userId);
        Date now = new Date();
        comment.setCreateTiem(now);
        comment.setAlbId(albId);
        comment.setImgId(imgId);
        //回复数
        comment.setArgs1("0");
        //点赞数
        comment.setArgs2("0");

        int comments = commentService.insert(comment);
        data.put("commentList", comments);

        RedisUtils redisUtils = RedisUtils.getInstance();

        if (commContent != null || !"".equals(commContent)) {
            if (commType == 0) {
                redisUtils.incrBy(StaticResource.SYS_INIT_ALBUM_COMMENT + albId, new Long(1));
            }

            if (commType == 1) {
                redisUtils.incrBy(StaticResource.SYS_INIT_IMAGE_COMMENT + imgId, new Long(1));
            }

            return returnResult(UsersEnum.COMMENT_SUCCESS.getId(), data, UsersEnum.COMMENT_SUCCESS.getValue());
        } else {
            return returnResult(UsersEnum.COMMENT_ERROR.getId(), data, UsersEnum.COMMENT_ERROR.getValue());
        }

    }


    /**
     * 评论回复列表
     *
     * @param commentId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getReplysList", method = RequestMethod.POST)
    public JSONObject getReplysList(@RequestParam String commentId, int pageNum) {
        PageBean<ReplysVO> commentVOs = iReplysService.getReplyList(commentId, pageNum);
        return returnResult(200, commentVOs, "");
    }


    /**
     * 模特个人详情
     *
     * @param modelId
     * @return
     */
    @RequestMapping(value = "/getModelsById", method = RequestMethod.POST)
    public JSONObject getModelsById(@RequestParam String modelId, @RequestParam(required = false) String userId) {
        Model model = iModelsService.selectByPrimaryKey(modelId);

        Map<String, String> par = new HashedMap();
        par.put("userId", userId);
        par.put("modelId", modelId);
        Attention attention = iUserExtService.findUserAttention(par);

        ModelVO modelVO = (ModelVO) ClazzUtils.copyBean(model, new ModelVO());
        modelVO.setAtten(attention == null ? false : true);
        return returnResult(200, modelVO, "");
    }

    /**
     * 模特列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getModelList", method = RequestMethod.POST)
    public JSONObject getModelList(int pageNum, int pageSize) {
        Map<String, Object> data = new HashMap();
        if (pageNum > 0) {
            PageBean<ModelsVO> modelsList = iModelsService.getModelList(pageNum, pageSize);
            return returnResult(200, modelsList, "");
        } else {
            return returnResult(UsersEnum.PAGE_PARAM_ERROR.getId(), data, UsersEnum.PAGE_PARAM_ERROR.getValue());
        }

    }


    /**
     * 模特历史专辑列表
     *
     * @param modelId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getModelAlbumList", method = RequestMethod.POST)
    public JSONObject getModelAlbumList(@RequestParam String modelId, String userId) {
        PageBean<ModelAlbumVO> modelAlbumList = iModelAlbumService.getModelAlbumList(modelId, userId);

        return returnResult(200, modelAlbumList, "");
    }

    /**
     * 获取单条评论
     */
    @ResponseBody
    @RequestMapping(value = "/getCommentById", method = RequestMethod.GET)
    public JSONObject getCommentById(@RequestParam String commentId) {
        Comment commennt = commentService.getCommentById(commentId);
        return returnResult(200, commennt, "");
    }

    /**
     * 点赞
     *
     * @param commentId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getLike", method = RequestMethod.POST)
    public JSONObject getLike(@RequestParam String commentId) {
        RedisUtils redisUtils = RedisUtils.getInstance();
        redisUtils.incrBy(StaticResource.SYS_INIT_UP + commentId, new Long(1));
        return returnResult(UsersEnum.COMMENT_UP.getId(), "", UsersEnum.COMMENT_UP.getValue());

    }

    /**
     * 关注
     *
     * @param attType
     * @param userId
     * @param modelId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAttention", method = RequestMethod.POST)
    public JSONObject getAttention(@RequestParam int attType, String userId, String modelId) {
        RedisUtils redisUtils = RedisUtils.getInstance();
        Map<String, String> data = new HashMap<String, String>();

        Attention attention = new Attention();
        attention.setUserId(userId);
        attention.setAttType(attType);
        if (attType == 0)
            attention.setModelId(modelId);
        if (attType == 1)
            attention.setAuthorId(modelId);

        Attention flagAtt = attentionService.findAttentionByIds(attention);
        if (flagAtt != null) {
            return returnResult(UsersEnum.ATTENTION_REPEAT_ERROR.getId(), data, UsersEnum.ATTENTION_REPEAT_ERROR.getValue());
        } else {
            attention.setAttId(UUIDUtils.getUUID());
            int num = attentionService.saveAttention(attention);
            if (num == 0) {
                return returnResult(UsersEnum.ATTENTION_DB_ERROR.getId(), data, UsersEnum.ATTENTION_DB_ERROR.getValue());
            }
        }
        if (!modelId.equals("")) {
            redisUtils.incrBy(StaticResource.SYS_INIT_ATTENTION + modelId, new Long(1));
            return returnResult(UsersEnum.ATTENTION_SUCCESS.getId(), data, UsersEnum.ATTENTION_SUCCESS.getValue());
        } else {
            return returnResult(UsersEnum.ATTENTION_ERROR.getId(), data, UsersEnum.ATTENTION_ERROR.getValue());

        }
    }


    /**
     * 查看收藏列表
     *
     * @param favoriteType
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getFavoriteList", method = RequestMethod.POST)
    public JSONObject getFavoriteList(@RequestParam int favoriteType, @RequestParam String userId, @RequestParam int pageNum, @RequestParam int pageSize) {
        if (favoriteType == 2) {
            PageBean<FavoriteVO> favoritelist = albumService.getAlbumList(userId, pageNum, pageSize);
            return returnResult(200, favoritelist, "");
        } else if (favoriteType == 1) {
            PageBean<FavoriteVO> favoritelist1 = iImagesService.getImageList(userId, pageNum, pageSize);
            return returnResult(200, favoritelist1, "");
        } else {
            return returnResult(UsersEnum.COLLECT_ARGS_ERROR.getId(), null, UsersEnum.COLLECT_ARGS_ERROR.getValue());
        }

    }

    /**
     * 查看关注列表
     *
     * @param attType
     * @param pageNum
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAttentionList", method = RequestMethod.POST)
    public JSONObject getAttentionList(@RequestParam int attType, @RequestParam String userId, @RequestParam int pageNum, @RequestParam int pageSize) {
        if (attType == 0) {
            PageBean<AttentionVO> attentionlist = iModelsService.getAttentionModelList(userId, pageNum, pageSize);
            return returnResult(200, attentionlist, "");
        } else if (attType == 1) {
            PageBean<AttentionVO> attentionlist1 = authorService.getAttentionAuthorList(userId, pageNum, pageSize);
            return returnResult(200, attentionlist1, "");
        } else {
            return returnResult(UsersEnum.ATTENTION_ERROR.getId(), null, UsersEnum.ATTENTION_ERROR.getValue());
        }
    }


    /**
     * 根据用户Id删掉关注的这条信息，同时对model关注数-1
     *
     * @param modelId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancleAttention", method = RequestMethod.POST)
    public JSONObject cancleAttentionList(@RequestParam String modelId, @RequestParam String userId) {
        attentionService.deleteAttention(userId, modelId);
        RedisUtils redisUtils = RedisUtils.getInstance();
        if (redisUtils.exists(StaticResource.SYS_INIT_ATTENTION + modelId)) {
            redisUtils.incrBy(StaticResource.SYS_INIT_ATTENTION + modelId, new Long(-1));
        }
        return returnResult(UsersEnum.ATTENTION_CANCLE_SUCCESS.getId(), "", UsersEnum.ATTENTION_CANCLE_SUCCESS.getValue());
    }

    /**
     * 图片收藏数和专辑收藏数
     *
     * @param imgId
     * @param albId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/setFavorite", method = RequestMethod.POST)
    public JSONObject setLike(@RequestParam String imgId, @RequestParam String albId, @RequestParam String userId, @RequestParam String modelId) {
        Favorite favorite = new Favorite();
        favorite.setFavoriteId(UUIDUtils.getUUID());
        favorite.setAlbId(albId);
        favorite.setImgId(imgId);
        favorite.setUserId(userId);
        favorite.setModelId(modelId);
        if (imgId != null && !"".equals(imgId)) {
            favorite.setFavoriteType(1);
        }
        if (albId != null && !"".equals(albId)) {
            favorite.setFavoriteType(2);
        }
        if (userFavouriteService.findFavoriteByIds(favorite) == null) {
            userFavouriteService.insert(favorite);
        } else {
            return returnResult(UsersEnum.COLLECT_ERROR.getId(), "", UsersEnum.COLLECT_ERROR.getValue());
        }
        RedisUtils redisUtils = RedisUtils.getInstance();
        //收藏数添加到缓存中。
        if (albId.equals("")) {
            redisUtils.incrBy(StaticResource.SYS_INIT_IMAGE_LIKE + imgId, new Long(1));
            return returnResult(UsersEnum.COLLECT_IMAGE_UP.getId(), "", UsersEnum.COLLECT_IMAGE_UP.getValue());
        } else {
            redisUtils.set(StaticResource.SYS_INIT_ALBUM_LIKE + albId, new Long(1));
            return returnResult(UsersEnum.COLLECT_ALBUM_UP.getId(), "", UsersEnum.COLLECT_ALBUM_UP.getValue());
        }
    }

    /**
     * 图片分享数和专辑分享数
     *
     * @param imgId
     * @param albId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getShare", method = RequestMethod.POST)
    public JSONObject getShare(@RequestParam String imgId, @RequestParam String albId) {
        RedisUtils redisUtils = RedisUtils.getInstance();
        if (albId.equals("")) {
            redisUtils.incrBy(StaticResource.SYS_INIT_IMAGE_SHARE + imgId, new Long(1));
            return returnResult(UsersEnum.SHARE_IMAGE_UP.getId(), "", UsersEnum.SHARE_IMAGE_UP.getValue());
        } else {
            redisUtils.incrBy(StaticResource.SYS_INIT_ALBUM_SHARE + albId, new Long(1));
            return returnResult(UsersEnum.SHARE_ALBUM_UP.getId(), "", UsersEnum.SHARE_ALBUM_UP.getValue());
        }
    }

    /**
     * 取消收藏
     *
     * @param ids
     * @param type
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancleFavourite", method = RequestMethod.POST)
    public JSONObject cancleAlbum(@RequestParam String ids, @RequestParam int type, @RequestParam String userId) {
        RedisUtils redisUtils = RedisUtils.getInstance();
        String[] result = ids.split(",");
        int resu = userFavouriteService.deletedFavorite(result, type, userId);
        if (resu > 0) {
            String redisKey = new String();
            for (int i = 0; i < result.length; i++) {
                if (type == 0) {
                    redisKey = StaticResource.SYS_INIT_ALBUM_LIKE + result[i];
                } else {
                    redisKey = StaticResource.SYS_INIT_IMAGE_LIKE + result[i];
                }

                if (redisUtils.exists(redisKey)) {
                    String cancleValue = redisUtils.getString(redisKey);
                    int cancleValueSubtract = Integer.valueOf(cancleValue) - 1;
                    String cancle = String.valueOf(cancleValueSubtract);
                    redisUtils.set(redisKey, cancle);
                } else {
                    redisUtils.set(redisKey, "-1");
                }
            }
        }
        if (type == 0) {
            return returnResult(UsersEnum.COLLECT_ALBUM_CANCLE.getId(), "", UsersEnum.COLLECT_ALBUM_CANCLE.getValue());
        } else {
            return returnResult(UsersEnum.COLLECT_IMAGE_CANCLE.getId(), "", UsersEnum.COLLECT_IMAGE_CANCLE.getValue());
        }
    }

    /**
     * 取消专辑收藏
     *
     * @param albId
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancleAlbum", method = RequestMethod.POST)
    public JSONObject cancleAlbum(@RequestParam String albId, @RequestParam String userId) {
        RedisUtils redisUtils = RedisUtils.getInstance();
        String[] result = albId.split(",");
        List<String> albIdList = Arrays.asList(result);
        userFavouriteService.deleteAlbumFavorite(albIdList, userId);
        for (int i = 0; i < result.length; i++) {
            String albIdVO = result[i];
            redisUtils.incrBy(StaticResource.SYS_INIT_ALBUM_LIKE + albIdVO, new Long(-1));
        }
        return returnResult(UsersEnum.COLLECT_ALBUM_CANCLE.getId(), "", UsersEnum.COLLECT_ALBUM_CANCLE.getValue());
    }

    /**
     * 取消图片收藏
     *
     * @param imgId
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancleImage", method = RequestMethod.POST)
    public JSONObject cancleImage(@RequestParam String imgId, @RequestParam String userId) {
        RedisUtils redisUtils = RedisUtils.getInstance();
        String[] result = imgId.split(",");
        List<String> albIdList = Arrays.asList(result);
        userFavouriteService.deleteFavorite(albIdList, userId);
        for (int i = 0; i < result.length; i++) {
            String imgIdVO = result[i];
            redisUtils.incrBy(StaticResource.SYS_INIT_IMAGE_LIKE + imgIdVO, new Long(-1));
        }
        return returnResult(UsersEnum.COLLECT_IMAGE_CANCLE.getId(), "", UsersEnum.COLLECT_IMAGE_CANCLE.getValue());
    }
}

